import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const dataDir = path.join(__dirname, '../../data');
const configPath = path.join(dataDir, 'config.json');

function ensureDataDir() {
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir, { recursive: true });
  }
}

export function readConfig() {
  ensureDataDir();
  if (!fs.existsSync(configPath)) {
    return { apiKey: '', baseUrl: '', defaultModel: '' };
  }
  try {
    const raw = fs.readFileSync(configPath, 'utf-8');
    const parsed = JSON.parse(raw);
    return {
      apiKey: parsed.apiKey || '',
      baseUrl: parsed.baseUrl || '',
      defaultModel: parsed.defaultModel || '',
    };
  } catch (e) {
    return { apiKey: '', baseUrl: '', defaultModel: '' };
  }
}

export function writeConfig(newConfig) {
  ensureDataDir();
  const existing = readConfig();
  const pickOrKeep = (incoming, current) => {
    if (incoming === undefined) return current;
    if (typeof incoming !== 'string') return current;
    const trimmed = incoming.trim();
    return trimmed === '' ? current : trimmed;
  };
  const merged = {
    apiKey: pickOrKeep(newConfig.apiKey, existing.apiKey),
    baseUrl: pickOrKeep(newConfig.baseUrl, existing.baseUrl),
    defaultModel: pickOrKeep(newConfig.defaultModel, existing.defaultModel),
  };
  fs.writeFileSync(configPath, JSON.stringify(merged, null, 2));
  return merged;
}

export function getConfigFilePath() {
  return configPath;
}


